package com.sf.gis.boot.rcboot.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.sf.gis.boot.rcboot.constants.Common;
import com.sf.gis.boot.rcboot.shiro.entity.SysUser;
import com.sf.gis.boot.rcboot.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JWTUtil {


    public static final long EXPIRE_TIME = SpringContextUtils.getBean(ShiroProperties.class).getJwtTimeOut() * 1000;
    public static final String MY_SECRET = "my_secret";

    /**
     * 生成 token
     *
     * @param username 用户名
     * @return token
     */
    public static String sign(String username,String password,Boolean rememberMe) {

        long expireTime = null != rememberMe && rememberMe ? EXPIRE_TIME : 30 * 60 * 1000 ;
        try {

            Date date = new Date(System.currentTimeMillis() + expireTime);
            Algorithm algorithm = Algorithm.HMAC256(MY_SECRET+password);
            String userinfo = Common.GSON.toJson(new SysUser().setUsername(username).setPassword(password));
            return JWT.create()
                    .withClaim("userinfo", userinfo)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("error：{}", e);
            return null;
        }
    }

    /**
     * 校验 token是否正确
     *
     * @param token  密钥
     * @return 是否正确
     */
    public static boolean verify(String token,String username,String password) {
        try {

            Algorithm algorithm = Algorithm.HMAC256(MY_SECRET+password);
            String userinfo = Common.GSON.toJson(new SysUser().setUsername(username).setPassword(password));
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("userinfo", userinfo)
                    .build();
            verifier.verify(token);
//            log.info("token is valid");
            return true;
        } catch (Exception e) {
            log.info("token is invalid{}", e.getMessage());
            return false;
        }
    }

}
